package com.whz.governance.http.ribbon.rule;

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.netflix.loadbalancer.AbstractServerPredicate;
import com.netflix.loadbalancer.PredicateKey;
import com.whz.generic.Constants;
import com.whz.governance.http.ribbon.context.RibbonFilterContextHolder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.util.StringUtils;

import javax.annotation.Nullable;
import java.util.Map;

/**
 * @author whz
 */
@val
@Slf4j
public class GreyDeployPredicate extends AbstractServerPredicate {

    @Override
    public boolean apply(@Nullable PredicateKey input) {
        return input != null
               && input.getServer() instanceof NacosServer;
        // && execute((NacosServer) input.getServer());
    }

    /**
     * 带灰度header的请求路由到 到灰度的服务,
     * 正常请求(没有灰度标志)的 路由到正常服务(没有灰度标志)
     */
    public static boolean execute(NacosServer server) {
        val attributes = RibbonFilterContextHolder.getCurrentContext().getAttributes();
        String headerVal = attributes.get(Constants.GREY_FLAG);
        final Map<String, String> metadata = server.getMetadata();
        val metaVal = metadata.get(Constants.GREY_FLAG);
        boolean result;
        if (StringUtils.isEmpty(headerVal)) {
            // 没有灰度标志,选择没有灰度标记 的服务
            result = StringUtils.isEmpty(metaVal);
        } else {
            result = headerVal.equalsIgnoreCase(metaVal);
        }
        log.info("grey test Predicate select server: {}, result: {}", server, result);
        return result;
    }
}